import * as mosca from 'mosca'
// import { port, wsPort, wsStatic } from './config.js'

const authenticate = function (client, username, password, callback) {
  if (username == "local@yigorw.cn" && password.toString() == "6549a894f15c0dc2e2bc56ae")
    callback(null, true)
  else
    callback(null, false)
}

const authorizePublish = function (client, topic, payload, callback) {
  const auth = true
  // set auth to :
  //  true to allow 
  //  false to deny and disconnect
  //  'ignore' to puback but not publish msg.
  callback(null, auth)
}

const authorizeSubscribe = function (client, topic, callback) {
  const auth = true
  // set auth to :
  //  true to allow
  //  false to deny 
  callback(null, auth)
}

const server = new mosca.Server({
  port: 1883, // tcp port
  http: {
    port: 8080, // ws port
    bundle: true,
    static: './',  // wsStatic
  },
  // backend: {
  //   type: 'redis',
  //   redis: require('redis'),
  //   db: 2,
  //   port: 6379,
  //   return_buffers: true, // to handle binary payloads
  //   host: "localhost"
  // },
  // persistence: {
  //   factory: mosca.persistence.Redis
  // },
})

server.on('ready', setup)

function setup() {
  server.authenticate = authenticate
  // server.authorizePublish = authorizePublish;
  // server.authorizeSubscribe = authorizeSubscribe;
  console.log(`Mosca server is up and running:${port}, ws port:${wsPort}`)
}

server.on("error", function (err) {
  console.log(err)
})

server.on('clientConnected', function (client) {
  console.log('Client Connected \t:= ', client.id)
})

server.on('published', function (packet, client) {
  let { topic, payload, messageId, qos, retain } = packet
  payload = payload.toString()
  if (!topic.startsWith('$SYS')) console.log("Published :=", { topic, payload, messageId, qos, retain, })
})

server.on('subscribed', function (topic, client) {
  console.log("Subscribed :=", topic, '<<<', client.id)
})

server.on('unsubscribed', function (topic, client) {
  console.log('unsubscribed := ', topic, '<<<', client.id)
})


server.on('clientDisconnecting', function (client) {
  console.log('clientDisconnecting := ', client.id)
})

server.on('clientDisconnected', function (client) {
  console.log('Client Disconnected := ', client.id)
})

export { server }

// server.on('published', function (packet, client) {
//   let { payload, messageId, qos, retain } = packet
//   payload = payload.toString()
//   console.log("Published :=", { messageId, qos, retain, payload, })
// })
// server.on('subscribed', function (topic, client) {
//   console.log("Subscribed :=", client.packet)
// })
// server.on('unsubscribed', function (topic, client) {
//   console.log('unsubscribed := ', topic)
// })